from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from user import models, seruser
from utils.tooljwt import tool
from utils.MyRedis import myredis
import random


# Create your views here.
class Reigister(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        phone = request.data.get('phone')
        email = request.data.get('email')
        code = request.data.get('code')
        kcode = myredis.get_str(phone)
        if kcode == code:
            user1 = models.User.objects.filter(phone=phone).first()
            if user1:
                return Response({'code': 100, 'msg': '用户已存在'})
            else:
                models.User.objects.create(name=username, password=password, phone=phone, email=email,
                                           code=code)
                return Response({'code': 200, 'msg': '注册成功'})
        else:
            return Response({'code': 100, 'msg': '验证码错误'})


class SendCode(APIView):
    def post(self, request):
        phone = request.data.get('phone')
        code = random.randint(100000, 999999)
        myredis.set_time_str(phone, 60, code)
        models.User.objects.filter(phone=phone).update(code=code)
        return Response({'code': 200, 'msg': '发送成功，请在60秒内输入', 'data': [phone, code]})


class Login(APIView):
    def post(self, request):
        way = request.data.get('way')
        if way == '0':
            username = request.data.get('username')
            password = request.data.get('password')
            user1 = models.User.objects.filter(name=username, password=password).first()
            if user1:
                token = tool.gettoken({'id': user1.id, 'username': user1.name})
                ser = seruser.UserSerializer(user1)
                return Response({'code': 200, 'msg': '登录成功', 'token': token, 'data': ser.data})
            else:
                return Response({'code': 100, 'msg': '用户名或密码错误'})
        elif way == '1':
            phone = request.data.get('phone')
            code = request.data.get('code')
            user1 = models.User.objects.filter(phone=phone).first()
            kcode = myredis.get_str(phone)
            if user1:
                if code == kcode:
                    token = tool.gettoken({'id': user1.id, 'username': user1.name})
                    return Response(
                        {'status': 200, 'msg': '登录成功', 'token': token, 'data': seruser.UserSerializer(user1).data})
                else:
                    return Response({'code': 100, 'msg': '验证码错误或已过期'})
            else:
                return Response({'code': 400, 'msg': '用户不存在'})
